package com.njtoyo.taxi.admin.utils;

import com.njtoyo.taxi.admin.library.common.GeoPoint;

import java.util.List;

public class RouteDistanceCalculator {

    private static final double EARTH_RADIUS = 6371; // 地球半径（公里）

    // 计算两点间距离（Haversine公式）
    public static double calculateDistance(double lat1, double lon1, double lat2, double lon2) {
        double lat1Rad = Math.toRadians(lat1);
        double lon1Rad = Math.toRadians(lon1);
        double lat2Rad = Math.toRadians(lat2);
        double lon2Rad = Math.toRadians(lon2);

        double latDiff = lat2Rad - lat1Rad;
        double lonDiff = lon2Rad - lon1Rad;

        double a = Math.pow(Math.sin(latDiff / 2), 2)
                + Math.cos(lat1Rad) * Math.cos(lat2Rad) * Math.pow(Math.sin(lonDiff / 2), 2);
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

        return EARTH_RADIUS * c; // 单位：公里
    }

    // 计算路线总距离（逐段累加）
    public static double calculateTotalDistance(List<GeoPoint> points) {
        if (points == null || points.size() < 2) {
            return 0; // 至少需要两个点才能计算距离
        }

        double totalDistance = 0;
        for (int i = 0; i < points.size() - 1; i++) {
            GeoPoint current = points.get(i);
            GeoPoint next = points.get(i + 1);
            totalDistance += calculateDistance(current.getLatitude(), current.getLongitude(), next.getLatitude(), next.getLongitude());
        }
        return totalDistance;
    }

}